<template>
    <el-dialog :title="dialogTitle" :visible.sync="isVisible">
        <el-form ref="initIndustryForm" :model="initIndustryForm" :rules="rules" label-width="100px">
            <el-form-item label="行业名称" prop="name">
                <el-input v-model="initIndustryForm.name" />
            </el-form-item>

            <el-form-item>
                <el-button type="primary" plain size="small" @click="submitForm('initIndustryForm')">保存</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
</template>
<script>
import initIndustryApi from '@/api/init/industry'
export default {
    name: 'Edit',
    props: {
        dialogVisible: {
            type: Boolean,
            default: false
        },
        type: {
            type: String,
            default: 'add'
        },
        title: {
            type: String,
            default: '添加'
        }
    },
    data() {
        return {
            // 因为不能直接修改 props 接收到的值，所以用一个变量来接收，修改这个变量
            dialogType: this.type,
            dialogTitle: this.title,
            initIndustryForm: {
                name: ''
            },
            rules: {
                name: [
                    { required: true, message: '请输入行业名称', trigger: 'blur' },
                    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
                ]
            }
        }
    },
    computed: {
        isVisible: {
            get() {
                return this.dialogVisible
            },
            set() {
                this.close()
            }
        }
    },
    methods: {
        close() {
            this.$emit('close')
        },
        submitForm(formName) {
            let _this = this
            this.$refs[formName].validate(valid => {
                if (valid) {
                    // 判断是添加还是修改
                    if (_this.dialogType == 'add') {
                        initIndustryApi.add(this.initIndustryForm).then(() => {
                            _this.isVisible = false
                            _this.$emit('success')
                        })
                    } else {
                        initIndustryApi.update(this.initIndustryForm).then(() => {
                            _this.isVisible = false
                            _this.$emit('success')
                        })
                    }
                } else {
                    return false
                }
            })
        },
        getInitIndustry(id) {
            // 清空表单
            this.resetForm('initIndustryForm')
            // 回显数据
            initIndustryApi.get(id).then(res => {
                this.initIndustryForm = res.data.data
            })
        },
        resetForm(formName) {
            this.$refs[formName].resetFields()
        }
    }
}
</script>
